<?php
/**
 * Controller class file.
 *
 * @author Pavel <dew.pavel.wo@gmail.com>
 */

/**
 * Controller is the base class for classes containing controller logic.
 */
class Controller
{
	/**
	 * @event ActionEvent an event raised right before executing a controller action.
	 * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
	 */
	const EVENT_BEFORE_ACTION = 'beforeAction';

	/**
	 * @event ActionEvent an event raised right after executing a controller action.
	 */
	const EVENT_AFTER_ACTION = 'afterAction';

	/**
	 * @var string the ID of this controller
	 */
	public $id;

	/**
	 * @var string the ID of the action that is used when the action ID is not specified
	 * in the request. Defaults to 'index'.
	 */
	public $defaultAction = 'index';

	/**
	 * @var string the ID of the module that is used when the module ID is not specified
	 * in the request. Defaults to 'content'.
	 */
	public $defaultModule = 'content';

	/**
	 * @var string|boolean the name of the layout to be applied to this controller's views.
	 * This property mainly affects the behavior of [[render()]].
	 * Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
	 * If false, no layout will be applied.
	 */
	public $layout;

	/**
	 * @var Action the action that is currently being executed.
	 */
	public $action;

	/**
	*  Format action name from URL parameter to method name
	*  @param string $name action name from URL parameter
	*  @return string method name
	*/
	private static function _formatName($name)
	{
		$name = str_replace(array('-','_','.'),' ', strtolower($name));
		$name = preg_replace("[^a-z0-9 ]",'',$name);
		return str_replace(' ','',ucwords($name));
	}

	/**
	 * Creates new controller instance by module and area
	 * @param string $area current area
	 * @param string $mod current module name
	 * @return Controller module controller instance
	 */
	public static function factory($area, $mod = "", $defmod = "content")
	{
		$area = ($area == '' ) ? "visitor" : $area ;

		if ( empty($mod) ) {
			$mod = $defmod;
		}

		$classFile = App::getAlias("@modules/$mod/$area").".php";

		if(!preg_match("/^\w+$/", $mod) or !file_exists( $classFile ) ){
			die("404 Not Found");
		}else{
			include( $classFile );
			$className = self::_formatName($mod)."_Controller_".ucfirst($area);
			$ctrl = new $className();
			return $ctrl;
		}
	}

}